package com.atguigu.day03;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Flink09_Transform_Filter_WithParm {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.从端口获取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        // 3.使用map 将端口发送过来的数据转为WaterSensor
        SingleOutputStreamOperator<WaterSensor> waterSensorMap = streamSource.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");
                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });

        //TODO 4.使用 filter过滤 过滤出id为sensor_1的数据
        SingleOutputStreamOperator<WaterSensor> fileter = waterSensorMap.filter(new MyFilterWithParam("sensor_2"));


        fileter.print();

        env.execute();
    }

    public static class MyFilterWithParam implements FilterFunction<WaterSensor>{

        String parm;

        public MyFilterWithParam(String parm) {
            this.parm = parm;
        }

        @Override
        public boolean filter(WaterSensor value) throws Exception {
            return value.getId().equals(parm);
        }
    }
}
